package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类 定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理支付超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ? ") //表示每分钟执行一次
    public void ProcessTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        //select * from orders where status = 待支付 and order_time < (当前时间 - 15min)
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        if(orders != null && orders.size() >0 ){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(Orders.OrderDelayCancelReson);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }

    }


    /**
     * 处理一直处于派送中 超时的订单 直接完成订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")  //每天凌晨1点触发一次
    public void ProcessDELIVERY_IN_PROGRESS_Order(){
        log.info("定时处理派送中订单：{}", LocalDateTime.now());

        //只需要把当前时间减少一个小时 就变成昨天的24点也就是今天的0点 就可以统一把昨天所有的订单进行处理了
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-1));

        if(ordersList != null && ordersList.size() >0 ){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }

    }

}
